<?php
class KhoiPDTestsController extends AppController{
	
	public function sudoku() {
		$start = microtime(true);
	
		$this->autoRender = false;
		$initialArray = array(
				array(4, 3, 5, 2, 6, 9, 7, 8, 1),
				array(6, 8, 2, 5, 7, 1, 4, 9, 3),
				array(1, 9, 7, 8, 3, 4, 5, 6, 2),
				array(8, 2, 6, 1, 9, 5, 3, 4, 7),
				array(3, 7, 4, 6, 8, 2, 9, 1, 5),
				array(9, 5, 1, 7, 4, 3, 6, 2, 8),
				array(5, 1, 9, 3, 2, 6, 8, 7, 4),
				array(2, 4, 8, 9, 5, 7, 1, 3, 6),
				array(7, 6, 3, 4, 1, 8, 2, 5, 9)
		);
	
		$result = $this->_sudoku($initialArray);
		var_dump($result);
	
		echo ' ---  runntime: ' . (microtime(true) - $start);
	}
	
private function _sudoku($srcArr) {
		$arrRow = array();
		$arrCol = array();
		$arrBox = array();
		for ($i = 0; $i < count($srcArr); $i++) {
			for ($j = 0; $j < count($srcArr[$i]); $j++) {
				$arrRow[$i][] = $srcArr[$i][$j];
				$arrCol[$j][] = $srcArr[$i][$j];
				
				$boxIndex = (floor(($i) / 3)) . (floor(($j) / 3));
				$arrBox[$boxIndex][] = $srcArr[$i][$j];
				
			}
			
			if (!$this->_checkSudoku($arrRow[$i])) {
				return false;
			}
		}
		
		//Check column is valid
		foreach ($arrCol as $value) {
			if (!$this->_checkSudoku($value)) {
				return false;
			}
		}
		
		//Check box is valid
		foreach ($arrBox as $value) {
			if (!$this->_checkSudoku($value)) {
				return false;
			}
		}
		
		return true;
	}
	
	private function _checkSudoku($arr) {
		if (count ($arr) != 9) {
			echo 'Khoi not enough<br/>';
			echo 'Check<pre>';
			print_r($arr);
			echo '</pre>';
			return false;
		}
		
		$int_arr = array_filter($arr, 'is_int');
		
		if ($int_arr !== $arr) {
			echo 'Khoi not int<br/>';
			echo 'Check<pre>';
			print_r($arr);
			echo '</pre>';
			return false;
		}
		
		$uni_arr = array_unique($arr);
		
		if ($uni_arr !== $arr) {
			echo 'Khoi not unique<br/>';
			echo 'Check<pre>';
			print_r($arr);
			echo '</pre>';
			return false;	
		}
		
		if (max($arr) != 9) {
			echo 'Khoi Max not 9<br/>';
			echo 'Check<pre>';
			print_r($arr);
			echo '</pre>';
			return false;	
		}
		
		if (min($arr) != 1) {
			echo 'Khoi Min not 1<br/>';
			echo 'Check<pre>';
			print_r($arr);
			echo '</pre>';
			return false;	
		}
		
		return true;
	}
	
}